package com.mingqi.enetconnected.net.webview;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.primary.MainActivity;
import com.mingqi.enetconnected.util.log.Log2FileUtils;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicConstants;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.tencent.sonic.sdk.SonicSessionConnection;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BrowserActivity extends AppCompatActivity {

    public final static String PARAM_URL = "param_url";

    public final static String PARAM_MODE = "param_mode";

    private SonicSession sonicSession;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String url = intent.getStringExtra(PARAM_URL);
      //  url = "http://vcc.hbasesoft.com:8062/oauth/authorize?client_id=340f2e51fb3b41f699d314548cb25be&scope=read%20write&response_type=code&redirect_uri=http://vcc.hbasesoft.com:8060/user/login";
        //    int mode = intent.getIntExtra(PARAM_MODE, -1);
        url="http://vcc.hbasesoft.com:8062/oauth/authorize?client_id=340f2e51fb3b41f699d314548cb25be8&scope=read%20write&response_type=code&redirect_uri=http%3A%2F%2Fsu0105.hbasesoft.com%3A8060%2Fuser%2Flogin";


        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        // init sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl sonicSessionClient = null;

        // if it's sonic mode , startup sonic session at first time
        //    if (MainActivity.MODE_DEFAULT != mode) { // sonic mode
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        sessionConfigBuilder.setSupportLocalServer(true);

        // if it's offline pkg mode, we need to intercept the session connection
//            if (MainActivity.MODE_SONIC_WITH_OFFLINE_CACHE == mode) {
//                sessionConfigBuilder.setCacheInterceptor(new SonicCacheInterceptor(null) {
//                    @Override
//                    public String getCacheData(SonicSession session) {
//                        return null; // offline pkg does not need cache
//                    }
//                });
//
//                sessionConfigBuilder.setConnectionInterceptor(new SonicSessionConnectionInterceptor() {
//                    @Override
//                    public SonicSessionConnection getConnection(SonicSession session, Intent intent) {
//                        return new OfflinePkgSessionConnection(BrowserActivity.this, session, intent);
//                    }
//                });
//            }

        // create sonic session and run sonic flow
        sonicSession = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            // throw new UnknownError("create session fail!");
            Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show();
        }
        //   }

        // start init flow ...
        // in the real world, the init flow may cost a long time as startup
        // runtime、init configs....
        setContentView(R.layout.activity_browser);


        // init webview
        WebView webView = (WebView) findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 判断url链接中是否含有某个字段，如果有就执行指定的跳转（不执行跳转url链接），如果没有就加载url链接
                if (url.contains("code=")) {
                    System.out.println("url==" + url);
                    String[] codes = url.split("code=");
                    String code = "";
                    if (codes.length == 2) {
                        code = codes[1];
                    }
                    System.out.println("code====" + code);
                    final String newUrl = "http://vcc.hbasesoft.com:8060/v1/oauth/token?";

                    final String postData = "seq=1535537009145&client_id=340f2e51fb3b41f699d314548cb25be8&code=" +
                            code +
                            "&grant_type=authorization_code&scope=read%20write&redirect_uri=http%3a%2f%2f%2fsu0105.hbasesoft.com%3a8%3a8060%2fuser%2flogin&refresh_token=";


                    String urls="http://vcc.hbasesoft.com:8060/v1/oauth/token?seq=1535537009145&client_id=340f2e51fb3b41f699d314548cb25be8&code=" +
                            code+
                            "&grant_type=authorization_code&scope=read%20write&redirect_uri=http%3a%2f%2fsu0105.hbasesoft.com%3a8060%2fuser%2flogin&refresh_token=";
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Call<String> call = OkGo.<String>post(newUrl + postData)
//                                    .tag(BrowserActivity.this)
//                                    .headers("username", "BATE00002")
//                                    .headers("password", "e10adc3949ba59abbe56e057f20f883e")
//                                    .converter(new StringConvert())
//                                    .adapt();
//                            Response<String> response = null;
//                            try {
//                                response = call.execute();
//                                if (response.isSuccessful())
//                                    System.out.println(" response.body()====" + response.body());
//                                System.out.println(" response.body()====" + response.getException());
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }).start();


//.headers("username", "340f2e51fb3b41f699d314548cb25be8")
//                            .headers("password", "e10adc3949ba59abbe56e057f20f883e")
                    OkGo.<String>post(urls).tag(BrowserActivity.this).execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {

                            Log2FileUtils.e(response.body().toString());
                            if (response.isSuccessful() && response.body() != null) {
                                if (!TextUtils.isEmpty(response.body() )) {
                               //     OkGo.getInstance().addCommonHeaders()
                                    Intent i = new Intent(BrowserActivity.this, MainActivity.class);
                                    startActivity(i);
                                }
                            }
                        }
                    });


                    return true;
                }
                return false;
            }

        });

        WebSettings webSettings = webView.getSettings();

        // add java script interface
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webSettings.setJavaScriptEnabled(true);
       // webSettings.setCacheMode();
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");

        // init webview settings
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);


        // webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(url);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        super.onDestroy();
    }


    private static class OfflinePkgSessionConnection extends SonicSessionConnection {

        private final WeakReference<Context> context;

        public OfflinePkgSessionConnection(Context context, SonicSession session, Intent intent) {
            super(session, intent);
            this.context = new WeakReference<Context>(context);
        }

        @Override
        protected int internalConnect() {
            Context ctx = context.get();
            if (null != ctx) {
                try {
                    InputStream offlineHtmlInputStream = ctx.getAssets().open("sonic-demo-index.html");
                    responseStream = new BufferedInputStream(offlineHtmlInputStream);
                    return SonicConstants.ERROR_CODE_SUCCESS;
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
            return SonicConstants.ERROR_CODE_UNKNOWN;
        }

        @Override
        protected BufferedInputStream internalGetResponseStream() {
            return responseStream;
        }

        @Override
        public void disconnect() {
            if (null != responseStream) {
                try {
                    responseStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getResponseCode() {
            return 200;
        }

        @Override
        public Map<String, List<String>> getResponseHeaderFields() {
            return new HashMap<>(0);
        }

        @Override
        public String getResponseHeaderField(String key) {
            return "";
        }
    }
}
